﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Report
{
    public class ReportUtil
    {
        public static void ReportError(Exception e)
        {
            WriteLog(e.Message + ":" + e.StackTrace);
            try
            {
                string hostname;
                string ip = GetIpAndHostName(out hostname);
                string log = buildErrorInfo(hostname, ip, e);
                ServerLog(log);
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message + ":" + ex.StackTrace);
            }
        }

        private static string GetIpAndHostName(out string hostname)
        {
            hostname = Dns.GetHostName();
            IPHostEntry localhost = Dns.GetHostEntry(hostname);
            if (localhost != null)
            {
                foreach (IPAddress item in localhost.AddressList)
                {
                    if (item.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return item.ToString();
                    }
                }
            }
            return "unkown";
        }

        private static void ServerLog(string strLog)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://10.3.1.134:8080/error");
            request.Method = "POST";

            byte[] postData = Encoding.UTF8.GetBytes(strLog);
            request.ContentType = "application/json";
            request.ContentLength = postData.Length;
            Stream myRequestStream = request.GetRequestStream();
            myRequestStream.Write(postData, 0, postData.Length);
            myRequestStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            myStreamReader.Close();
            myResponseStream.Close();
        }

        private static void WriteLog(string strLog)
        {
            string sFilePath = AppDomain.CurrentDomain.BaseDirectory + "\\log";
            string sFileName = sFilePath + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            if (!Directory.Exists(sFilePath))
            {
                Directory.CreateDirectory(sFilePath);
            }

            FileStream fs;
            StreamWriter sw;
            if (File.Exists(sFileName))
            {
                fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);
            }
            else
            {
                fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);
            }
            sw = new StreamWriter(fs);
            sw.WriteLine(string.Format("[{0}]{1}\r\n", DateTime.Now.ToString("T"), strLog));
            sw.Close();
            fs.Close();
        }

        private static string buildErrorInfo(string hostname, string ip, Exception e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");

            sb.Append("\"hostname\":\"");
            sb.Append(hostname);
            sb.Append("\",");

            sb.Append("\"ip\":\"");
            sb.Append(ip);
            sb.Append("\",");

            sb.Append("\"message\":\"");
            sb.Append(e.Message);
            sb.Append("\",");

            sb.Append("\"stackTrace\":\"");
            sb.Append(e.StackTrace);
            sb.Append("\"");

            sb.Append("}");

            return sb.ToString();
        }
    }
}
